import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.SwingConstants;


public class AdminEditShowingsPanel extends JPanel {
	private static final long serialVersionUID = 87760158559354096L;
	private static final int ADD = 1;
	private static final int DELETE = 2;
	private static final int EDIT = 3;

	private JTable table;
	private final DatabaseInfo db_info;
	private ArrayList<ShowingRow> showing_list;
	private JScrollPane scrolly;

	private AddEditMovieDialog add_dialog;
	private AddEditMovieDialog edit_dialog;
	private AdminEditShowingsPanel aepanel;
	private int the_button;

	private String my_cinema;
	private String my_title;
	private int my_time;

	public AdminEditShowingsPanel(DatabaseInfo the_db_info) {
		db_info = the_db_info;
		my_cinema = getQuery("SELECT members.adminFor FROM members WHERE members.accountID='"
				+ db_info.getAccountID() + "';", true);
		add_dialog = new AddEditMovieDialog(the_db_info, "add");
		edit_dialog = new AddEditMovieDialog(the_db_info, "edit");
		aepanel = this;
		createAndShowGUI();
	}

	/**
	 * Create the panel.
	 */
	public void createAndShowGUI() {		
		setLayout(null);

		JButton btnDelete = new JButton("Delete");
		btnDelete.setBounds(655, 330, 112, 23);
		btnDelete.addActionListener(new ModifyListener());
		add(btnDelete);

		JButton btnAddMovie = new JButton("Add Movie");
		btnAddMovie.setBounds(400, 330, 112, 23);
		btnAddMovie.addActionListener(new ModifyListener());
		add(btnAddMovie);

		JButton btnEditMovie = new JButton("Edit Movie");
		btnEditMovie.setBounds(527, 330, 112, 23);
		btnEditMovie.addActionListener(new ModifyListener());
		add(btnEditMovie);

		JLabel lblFindShowings = new JLabel("Edit Cinema Showings");
		lblFindShowings.setFont(new Font("Tahoma", Font.BOLD, 24));
		lblFindShowings.setBounds(270, 0, 300, 50);
		add(lblFindShowings);

		JLabel cinema_name = new JLabel(my_cinema);
		cinema_name.setHorizontalAlignment(SwingConstants.CENTER);
		cinema_name.setFont(new Font("Tahoma", Font.PLAIN, 16));
		cinema_name.setBounds(270, 48, 278, 14);
		add(cinema_name);

		createAddScrollPane(new JTable());
		refreshTable();
	}

	private void createAddScrollPane(JTable table) {
		table.addMouseListener(new TableListener());
		scrolly = new JScrollPane(table);
		scrolly.setBounds(10, 70, 761, 250);
		add(scrolly);
	}

	/**
	 * Executes a given query and returns the results;
	 * @param query The query to execute;
	 * @return The result of the query. Returns <code>null</code> if there
	 * 			was an exception thrown.
	 */
	private String getQuery(String query, boolean parse) {
		Db db = Db.getDb();
		String result = null;

		try {
			if (!parse)
				result = db.executeQuery(db_info.server, db_info.database, query, 
						db_info.user_name, db_info.password);
			else {
				result = db.executeQuery2(db_info.server, db_info.database, query, 
						db_info.user_name, db_info.password);
				result = result.replace("@", "");
			}

		} catch (Exception e1) {
			System.out.println(e1.getMessage());
			e1.printStackTrace();
		}

		return result;
	}

	private ArrayList<String> splitRowStrings(String the_data) {
		ArrayList<String> ret = new ArrayList<String>();

		while(0 < the_data.length()) {
			int io = the_data.indexOf('\r');
			String s;
			if(0 > io)
				s = the_data.trim();
			else
				s = the_data.substring(0,io).trim();

			ret.add(s);

			if(0 > io)
				break;
			the_data = the_data.substring(io,the_data.length()).trim();
		}
		return ret;
	}

	private String[] splitString(String header_string) {
		header_string = header_string.trim();
		String[] temp = header_string.split("\t");

		int valid_count = 0;
		for(int i = 0 ; i < temp.length ; i++) {
			temp[i] = temp[i].trim();
			if(0 < temp[i].length())
				valid_count++;
		}

		String[] ret = new String[valid_count];
		int j = 0;
		for(int i = 0 ; i < temp.length ; i++) {
			if(0 < temp[i].length())
				ret[j++] = temp[i];
		}
		return ret;
	}

	private String convertTitle(final String str) {
		if(str.equals("title")) return "Movie";
		else if(str.equals("time")) return "Time";

		return str; //default
	}

	/**
	 * Executes a given query and returns the results;
	 * @param query The query to execute;
	 * @return The result of the query. Returns <code>null</code> if there
	 * 			was an exception thrown.
	 */
	private void modifyTableData(String query) {
		Db db = Db.getDb();
		try {
			db.executeNonQuery(db_info.server, db_info.database, query, 
					db_info.user_name, db_info.password);
		} catch (Exception e1) {
			
			JOptionPane.showMessageDialog(null,
				    "There was a time conflict with the movie selected.",
				    "Error",
				    JOptionPane.ERROR_MESSAGE);
		}
	}

	public void modifyTable() {
		String query = null;
		switch(the_button) {
		case ADD:
			query = "INSERT INTO showings " +
					"VALUES ('"+ my_cinema + "','"+ add_dialog.title + "','"+ add_dialog.time +"');";
			break;
		case DELETE:
			query = "DELETE FROM showings " +
					"WHERE title='"+ my_title +"' AND cName='"+ my_cinema + "' AND time='"+ my_time + "';";
			break;
		case EDIT:
			query = "UPDATE showings " +
					"SET title='"+ edit_dialog.title +"', time='"+ edit_dialog.time +"'" +
					"WHERE title='"+ my_title +"' AND time='"+ my_time + "';";
			break;
		}
		modifyTableData(query);
		refreshTable();
	}

	private void refreshTable() {

		final int column_count = 2;
		final int row_count;
		String rc = getQuery("SELECT COUNT(cName) FROM showings WHERE cName ='"
				+ my_cinema + "';", false);
		rc = rc.substring(rc.indexOf('\r'), rc.length()).trim();
		row_count = Integer.parseInt(rc);

		String query = "SELECT showings.title, showings.time FROM showings WHERE cName ='"
				+ my_cinema + "';";
		String result = getQuery(query, false);

		if(null != result) {
			String header_line = result.substring(0, result.indexOf('\r'));

			String[] column_names = splitString(header_line);
			for(int i = 0 ; i < column_names.length ; i++)
				column_names[i] = convertTitle(column_names[i]);

			result = result.substring(result.indexOf('\r'),result.length()).trim();
			Object[][] table_data = new Object[row_count][column_count];
			showing_list = new ArrayList<ShowingRow>();

			int x = 0, y = 0;
			ArrayList<String> row_strings = splitRowStrings(result);

			ShowingRow.edit_admin = true;
			for(String s : row_strings) {
				x = 0;
				ShowingRow row = new ShowingRow(s);
				showing_list.add(row);
				table_data[y][x++] = row.getTitle();
				table_data[y][x++] = row.getTimeString();
				y++;
			}
			ShowingRow.edit_admin = false;


			table = new JTable(table_data, column_names);
			table.getColumnModel().getColumn(0).setPreferredWidth(250);
			table.getColumnModel().getColumn(1).setPreferredWidth(100);
			//table.setPreferredScrollableViewportSize(new Dimension(500, 70));
			table.setFillsViewportHeight(true);
			table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


			this.remove(scrolly);
			createAddScrollPane(table);
		}
	}

	private int getTimeInt(String s) {
		int time = 0;
		int lastTwo = 0;
		int firstTwo = 0;
		String temp = s.replace(":", "");
		if (s.contains("AM")) {
			temp = temp.replace(" AM", "");
			time = Integer.parseInt(temp);
			lastTwo = time % 100;
			firstTwo = time / 100;
			if (lastTwo < 60 && firstTwo < 24) {
				if (time >= 1200 && time < 1300) {
					time = 0 + lastTwo;
				}
			} 
		} else {
			temp = temp.replace(" PM", "");
			time = Integer.parseInt(temp);
			lastTwo = time % 100;
			firstTwo = time / 100;
			if (lastTwo < 60 && firstTwo < 24) {
				if (time >= 1200 && time < 1300) {
					time = 1200 + lastTwo;
				} else {
					time = time + 1200;
				}
			}
		}
		return time;
	}

	private class TableListener extends MouseAdapter {

		@Override
		public void mouseClicked(MouseEvent e) {
			if (table.getSelectedRow() > -1 || table.getSelectedColumn() > -1) {
				int col = table.getSelectedColumn();
				int row = table.getSelectedRow();

				if (table.getColumnName(col).equals("Movie")) {
					my_title = (String) table.getValueAt(row, col);
					//my_time = (String) table.getValueAt(row, col + 1);
					my_time = getTimeInt((String) table.getValueAt(row, col + 1));
				} else if (table.getColumnName(col).equals("Time")) {
					my_time = getTimeInt((String) table.getValueAt(row, col));
					//my_time = (String) table.getValueAt(row, col);
					my_title = (String) table.getValueAt(row, col - 1);
				}
			}
		}

	}

	private class ModifyListener implements ActionListener {
		@Override

		public void actionPerformed(ActionEvent e) {
			JButton button = ((JButton) e.getSource());
			if (button.getText().equals("Add Movie")) { 
				if (!add_dialog.isVisible()) {
					add_dialog.setVisible(true);
					//add_dialog.addConfirmListener(new ConfirmListener());
					add_dialog.setAdminEditPanel(aepanel);
					the_button = ADD;
				}
			} else if(button.getText().equals("Edit Movie")) {
				if (table.getSelectedRow() > -1 || table.getSelectedColumn() > -1) {
					if (!edit_dialog.isVisible()) {
						edit_dialog.setVisible(true);
						edit_dialog.setCurrentMovieTime(my_title, my_time);
						edit_dialog.setAdminEditPanel(aepanel);
						the_button = EDIT;
					}
				} else {
					JOptionPane.showMessageDialog(null,
							"Choose a row to edit.",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
			} else if(button.getText().equals("Delete")) {
				if (table.getSelectedRow() > -1 || table.getSelectedColumn() > -1) {
					the_button = DELETE;
					modifyTable();
				} else {
					JOptionPane.showMessageDialog(null,
							"Choose a row to delete.",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
	}
}
